import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { TournamentState, TournamentConfig, Team } from '../types.ts';
import { TrophyIcon } from '../components/icons/TrophyIcon.tsx';
import { ArrowLeftIcon } from '../components/icons/ArrowLeftIcon.tsx';
import { UsersIcon } from '../components/icons/UsersIcon.tsx';
import * as api from '../utils/api.ts';

const GroupsPage: React.FC = () => {
  const [tournamentState, setTournamentState] = useState<TournamentState | null>(null);
  const [tournamentConfig, setTournamentConfig] = useState<TournamentConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const drawnCount = React.useMemo(() => {
    return tournamentState?.drawn_captains?.length || 0;
  }, [tournamentState]);

  // 获取当前轮次的实际参与队伍数
  const getCurrentRoundTeamsCount = (): number => {
    if (!tournamentState?.draw_stage || !tournamentConfig?.rounds) {
      return tournamentConfig?.total_teams || 10;
    }

    const currentStage = tournamentState.draw_stage;
    const roundConfig = tournamentConfig.rounds.find(r => r.name === currentStage);

    if (!roundConfig) {
      return tournamentConfig?.total_teams || 10;
    }

    // 如果是第一轮，返回总队伍数
    if (currentStage === tournamentConfig.rounds[0]?.name) {
      return tournamentConfig?.total_teams || 10;
    }

    // 如果是复活赛，计算有资格参与的队伍数
    if (roundConfig.type === 'revival') {
      // 复活赛的参与队伍数 = 对应主要轮次的淘汰队伍数
      const mainRoundName = currentStage.replace('_revival', '_main');
      const eliminatedTeams = getEliminatedTeamsCount(mainRoundName);
      return eliminatedTeams;
    }

    // 如果是主要轮次，计算前面轮次的晋级队伍数
    return getAdvancedTeamsCount(currentStage);
  };

  // 获取指定轮次的淘汰队伍数
  const getEliminatedTeamsCount = (roundName: string): number => {
    if (!tournamentState?.matches) return 0;

    const roundMatches = tournamentState.matches.filter(m => m.round === roundName && m.completed);
    return roundMatches.length; // 每场比赛淘汰1支队伍
  };

  // 获取有资格参与当前轮次的队伍数
  const getAdvancedTeamsCount = (currentRound: string): number => {
    if (!tournamentConfig?.rounds) return 0;

    const currentRoundIndex = tournamentConfig.rounds.findIndex(r => r.name === currentRound);
    if (currentRoundIndex <= 0) return tournamentConfig?.total_teams || 10;

    // 计算前面所有轮次的晋级队伍数
    let advancedCount = tournamentConfig.total_teams || 10;

    for (let i = 0; i < currentRoundIndex; i++) {
      const round = tournamentConfig.rounds[i];
      if (round.type === 'main') {
        advancedCount = round.advance_count;
      } else if (round.type === 'revival') {
        advancedCount += round.advance_count;
      }
    }

    return advancedCount;
  };

  const totalTeams = getCurrentRoundTeamsCount();

  // 初始化数据
  useEffect(() => {
    const initializeData = async () => {
      try {
        const [statusResponse, configResponse] = await Promise.all([
          api.getTournamentStatus(),
          api.getTournamentConfig()
        ]);

        if (statusResponse.success && statusResponse.tournament_state) {
          setTournamentState(statusResponse.tournament_state);
        }

        if (configResponse.success && configResponse.config) {
          setTournamentConfig(configResponse.config);
        }

        setError(null);
      } catch (error) {
        console.error('初始化数据失败:', error);
        setError('加载数据失败，请刷新页面重试');
      } finally {
        setLoading(false);
      }
    };

    initializeData();
  }, []);

  // 定期刷新比赛数据
  useEffect(() => {
    const interval = setInterval(async () => {
      try {
        const statusResponse = await api.getTournamentStatus();
        if (statusResponse.success && statusResponse.tournament_state) {
          setTournamentState(statusResponse.tournament_state);
        }
      } catch (error) {
        console.error('刷新比赛数据失败:', error);
      }
    }, 5000); // 每5秒刷新一次

    return () => clearInterval(interval);
  }, []);

  // 获取当前轮次显示名称
  const getRoundDisplayName = (round: string): string => {
    if (round === 'completed') return '比赛结束';

    if (tournamentConfig?.rounds) {
      const roundConfig = tournamentConfig.rounds.find(r => r.name === round);
      if (roundConfig) {
        return roundConfig.display_name;
      }
    }

    return round; // 如果找不到配置，返回原始名称
  };

  // 获取当前轮次的分组数据
  const getCurrentRoundGroups = (): { [key: string]: Team[] } => {
    if (!tournamentState?.draw_stage) return {};

    const currentStage = tournamentState.draw_stage;
    const groupsKey = `${currentStage}_groups`;

    return (tournamentState as any)[groupsKey] || {};
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center">
        <div className="text-white text-xl">加载中...</div>
      </div>
    );
  }

  if (!tournamentState) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center">
        <div className="text-center">
          <div className="text-white text-xl mb-4">比赛尚未开始</div>
          <div className="text-white/70 text-sm">请等待管理员开启比赛</div>
        </div>
      </div>
    );
  }

  const currentGroups = getCurrentRoundGroups();

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex flex-col p-4 relative overflow-hidden">
      {/* 背景装饰 */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute -top-40 -right-40 w-80 h-80 bg-blue-500/10 rounded-full blur-3xl"></div>
        <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-purple-500/10 rounded-full blur-3xl"></div>
        <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-96 h-96 bg-yellow-500/5 rounded-full blur-3xl"></div>
      </div>

      {/* 导航栏 */}
      <nav className="flex items-center justify-between mb-6 z-10">
        <Link
          to="/"
          className="flex items-center gap-2 px-4 py-2 bg-white/10 backdrop-blur-sm rounded-lg border border-white/20 text-white hover:bg-white/20 hover:border-white/30 transition-all duration-300"
        >
          <ArrowLeftIcon className="w-5 h-5" />
          <span>返回抽签</span>
        </Link>

        <div className="flex items-center gap-2">
          <TrophyIcon className="w-6 h-6 text-yellow-400" />
          <h1 className="text-xl font-bold text-white">抽签情况</h1>
        </div>

        <div className="w-24"></div> {/* 占位符，保持居中 */}
      </nav>

      {/* 当前轮次信息 */}
      <div className="text-center mb-8 z-10">
        <div className="bg-white/10 backdrop-blur-sm rounded-xl p-6 border border-white/20 max-w-2xl mx-auto">
          <h2 className="text-2xl font-bold text-white mb-4">
            {getRoundDisplayName(tournamentState.current_round)}
          </h2>

          {tournamentState.draw_enabled ? (
            <div className="space-y-4">
              <div className="text-green-300 font-semibold">
                ✓ {getRoundDisplayName(tournamentState.draw_stage || tournamentState.current_round)}抽签进行中
              </div>
              <div className="flex justify-center items-center gap-6">
                <div className="text-center">
                  <div className="text-3xl font-bold text-green-400">{drawnCount}</div>
                  <div className="text-sm text-white/70">已抽签队伍</div>
                </div>
                <div className="text-white/50 text-2xl">/</div>
                <div className="text-center">
                  <div className="text-3xl font-bold text-blue-400">{totalTeams}</div>
                  <div className="text-sm text-white/70">总队伍数</div>
                </div>
              </div>
              <div className="mt-4">
                <div className="w-full bg-white/20 rounded-full h-2">
                  <div
                    className="bg-gradient-to-r from-green-500 to-blue-500 h-2 rounded-full transition-all duration-500"
                    style={{ width: `${(drawnCount / totalTeams) * 100}%` }}
                  ></div>
                </div>
              </div>
            </div>
          ) : (
            <div className="text-red-300 font-semibold">
              ⏸ 抽签暂停中，请等待管理员开启
            </div>
          )}
        </div>
      </div>

      {/* 分组显示 */}
      <main className="flex-grow z-10">
        {Object.keys(currentGroups).length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 max-w-6xl mx-auto">
            {Object.entries(currentGroups).map(([groupName, teams]) => (
              <div key={groupName} className="bg-white/10 backdrop-blur-sm rounded-xl p-6 border border-white/20">
                <div className="flex items-center gap-3 mb-4">
                  <div className="w-12 h-12 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full flex items-center justify-center">
                    <span className="text-white font-bold text-xl">{groupName}</span>
                  </div>
                  <div>
                    <h3 className="text-xl font-bold text-white">{groupName} 组</h3>
                    <p className="text-white/70 text-sm">{teams.length} 支队伍</p>
                  </div>
                </div>

                <div className="space-y-3">
                  {teams.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-8 text-white/50">
                      <UsersIcon className="w-12 h-12 mb-2" />
                      <p>等待队伍加入...</p>
                    </div>
                  ) : (
                    teams.map((team, index) => (
                      <div key={team.id} className="bg-white/10 rounded-lg p-3 border border-white/10">
                        <div className="flex items-center justify-between">
                          <div>
                            <div className="font-semibold text-white">{team.name}</div>
                            <div className="text-white/70 text-sm">队长: {team.captain}</div>
                          </div>
                          <div className="text-white/50 text-sm">#{index + 1}</div>
                        </div>
                      </div>
                    ))
                  )}
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-12">
            <div className="bg-white/10 backdrop-blur-sm rounded-xl p-8 border border-white/20 max-w-md mx-auto">
              <UsersIcon className="w-16 h-16 text-white/50 mx-auto mb-4" />
              <h3 className="text-xl font-bold text-white mb-2">暂无分组数据</h3>
              <p className="text-white/70">
                {tournamentState.draw_enabled ? '等待队长开始抽签...' : '等待管理员开启抽签...'}
              </p>
            </div>
          </div>
        )}
      </main>

      {/* 底部操作区 */}
      <footer className="mt-8 text-center z-10">
        <div className="bg-white/10 backdrop-blur-sm rounded-xl p-6 border border-white/20">
          <p className="text-white/70 mb-4">
            {drawnCount >= totalTeams ? '🎉 本轮抽签已完成！' :
             tournamentState.draw_enabled ? '抽签进行中...' : '等待管理员开启抽签'}
          </p>
          {tournamentState.draw_enabled && (
            <Link
              to="/"
              className="inline-flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white font-semibold rounded-lg transition-all duration-300 hover:scale-105"
            >
              <span>继续抽签</span>
            </Link>
          )}
        </div>
      </footer>

      {/* 错误提示 */}
      {error && (
        <div className="fixed top-4 right-4 bg-red-500/90 backdrop-blur-sm text-white px-4 py-3 rounded-lg shadow-lg z-50 border border-red-400">
          {error}
        </div>
      )}
    </div>
  );
};

export default GroupsPage;
